package nr.nodehost;
/**
 * Add by hengGuo 2023.11.15
 * function: listen to sockets of other nodehost and add to hashmap
 *
 * called by NodeHostApplication.java
 * */

import nr.nodehost.service.AsyncTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;

@Component
@EnableAsync
public class NodeHostListener {
    private int port;

    private Dispatcher dispatcher;

    @Autowired
    private AsyncTaskService taskService;

    // getPort方法
    public int getPort() {
        return this.port;
    }
    @Async
    public void run(){
        // 用serversocket的accept方法监听socket链接并将已经存在的链接记录进nodehostsocketmap
        try(ServerSocket serverSocket = new ServerSocket(this.getPort())) {
            while (true) {
                Socket clientSocket = serverSocket.accept();
                InetSocketAddress clientAddress = (InetSocketAddress) clientSocket.getRemoteSocketAddress();
                System.out.println(clientAddress.toString() + " connected");
                System.out.println("其他组件发送给我socket请求:"+clientAddress);
                new Thread(() -> {
                    try {
                        nodehostrunReceiver(clientSocket, dispatcher);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }).start();
                System.out.println("receive thread running...");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // runReveiver
    public void nodehostrunReceiver(Socket clientSocket, Dispatcher dispatcher) throws IOException {
        taskService.ListenToOtherNodeHost(clientSocket, dispatcher);
    }
}